package com.aaa.system.service.impl;

import com.aaa.entity.User;
import com.aaa.system.dao.DictDataDao;
import com.aaa.system.dao.DictTypeDao;
import com.aaa.system.dao.UserDao;
import com.aaa.system.service.IDictDataService;
import com.aaa.utils.JWTUtils;
import com.aaa.utils.WebUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aaa.entity.DictData;
import com.aaa.entity.DictType;
import com.aaa.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author L
 * @since 2023-03-21
 */
@Service
public class DictDataServiceImpl extends ServiceImpl<DictDataDao, DictData> implements IDictDataService {

    @Autowired
    private DictDataDao dictDataDao;

    @Autowired
    private DictTypeDao dictTypeDao;

    @Resource
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result<List<DictData>> findByType(String type) {
        try{
            //获取缓存中的对应的状态
            String s = redisTemplate.opsForValue().get(type);
            if (StringUtils.hasText(s)){
                //如果缓存中不为空，那么就直接从缓存中进行查询，并转化为DictData对象
                List<DictData> dictDataList = JSON.parseArray(s, DictData.class);
                return new Result<>(200,"缓存中查询所有状态成功",dictDataList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //否则就从数据库中再次查询
        QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type",type);
        List<DictData> dictData = dictDataDao.selectList(queryWrapper);
        return new Result<>(200,"查询所有状态成功",dictData);
    }


    @Override
    public Result<String> cacheAsync() {
        //查询所有的字典类型
        QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        List<DictType> dictTypes = dictTypeDao.selectList(queryWrapper);

        //循环遍历所有字典类型
        for (DictType dictType : dictTypes) {
            //查询所有的字典数据
            QueryWrapper<DictData> dataQueryWrapper = new QueryWrapper<>();
            dataQueryWrapper.eq("status",0);
            dataQueryWrapper.eq("dict_type",dictType.getDictType());
            List<DictData> dictData = dictDataDao.selectList(dataQueryWrapper);
            //存入缓存中，key值为字典类型，value值为每个对应的字典数据对象
            redisTemplate.opsForValue().set(dictType.getDictType(), JSON.toJSONString(dictData));
        }
        return new Result<>(200,"缓存同步成功");
    }

    @Override
    public Result<IPage<DictData>> selectAll(Integer current, Integer size, DictData dictData) {
        IPage<DictData> page = new Page<>(current,size);
        QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(dictData.getDictType())){
            queryWrapper.like("dict_type",dictData.getDictType());
        }
        if (StringUtils.hasText(dictData.getDictLabel())){
            queryWrapper.like("dict_label",dictData.getDictLabel());
        }
        if (Objects.nonNull(dictData.getStatus())){
            queryWrapper.eq("status",dictData.getStatus());
        }
        IPage<DictData> dictDataIPage = dictDataDao.selectPage(page,queryWrapper);
        return new Result<>(200,"查询所有字典数据成功",dictDataIPage);
    }

    @Override
    public Result<Boolean> saveOrUpdateDictData(DictData dictData) {
        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        //通过token获取登录用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User userByToken = userDao.selectOne(queryWrapper);

        if (Objects.nonNull(dictData.getDictCode())){
            //如果存在字典数据编码就是修改数据
            dictData.setUpdateTime(LocalDateTime.now());
            dictData.setUpdateBy(userByToken.getUserName());
            int i = dictDataDao.updateById(dictData);
            return new Result<>(200,"修改信息成功",i>0?true:false);
        }else {
            //如果没有字典数据编码就是添加数据
            dictData.setCreateTime(LocalDateTime.now());
            dictData.setCreateBy(userByToken.getUserName());
            int insert = dictDataDao.insert(dictData);
            return new Result<>(200,"添加信息成功",insert>0?true:false);
        }
    }

    @Override
    public Result<Boolean> deleteDictDataByIds(Long[] dictCodes) {
        Boolean b = null;
        if (dictCodes.length>0){
            b = dictDataDao.batchByIds(dictCodes);
        }
        return new Result<>(200,"删除成功",b);

    }
}
